package wiki.kaizen.cloud.security.session.support.realm;

import lombok.Setter;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.iherus.shiro.cache.redis.RedisCache;
import wiki.kaizen.cloud.security.session.support.service.LockedUserService;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 登录失败次数限制
 * @author xeepoo
 * */
public class PasswordCredentialsMatcher extends HashedCredentialsMatcher {
    /**
     * 登录失败次数
     */
    @Setter
    private Short max;

    /*
    *redis缓存
    * */
    @Setter
    private RedisCache<String, AtomicInteger> cache;

    @Setter
    private LockedUserService userService;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        if (token instanceof NoPasswordToken){
            return true;
        }
        String username = token.getPrincipal().toString();

        AtomicInteger count = cache.get(username);
        if (count==null){
            count = new AtomicInteger(0);

        }
        if (count.incrementAndGet()>max){
            userService.lock(username);
            throw new LockedAccountException("用户已被锁定");
        }
        //判断用户名密码是否正确
        boolean match = super.doCredentialsMatch(token, info);
        if (match){//匹配成功删除 缓存计数器
            cache.remove(username);
        }else{
            cache.put(username,count);
        }

        return match;
    }
}
